<?php

require_once 'classes/LightPressPlugin.php';

class AutoMetaFrontend extends LightPressPlugin {
    
    var $constructor_args = array(
        'replace_tags'   => 'Replaced the default LP post tags with the AutoMeta tags instead of extending them',
        'tags_in_feeds' => 'Retrieve tags in feeds instead of only retrieving them for blog pages'
        );
    var $default_context = LP_CONTEXT_ALL;
    var $description = 'A frontend for the AutoMeta WP plugin by Rich Boakes. This plugin only works if AutoMeta is correctly installed and activated in WP.';
    var $textareas = array();
    
    var $active = true;
    var $hooks = array('get_posts_loop');
    
    var $replace_tags = false;
    var $tags_in_feeds = true;
    
    var $_quotes = array("\x27", "\x22", "\x60", "\t", "\n", "\r", " ", ",", ".", "/", "�", "#", ";", ":", "@", "~", "[","]","{","}","=","-","+",")","(","*","&","^","%",'$',"�","<",">","?","!");
    
    function AutoMetaFrontend(&$frontend, $args, $dummy_run=false) {
        
        $this->LightPressPlugin($frontend, $args, $dummy_run);
        if (!$dummy_run && !$this->tags_in_feeds && $frontend->view_type != 'html')
            $this->active = false;
    }
    
    function &_get_tags($post_id) {
        
        $db =& $this->_frontend->db;
        $tags = array();
        
        $q = "select meta_value from {$this->_frontend->tables['postmeta']} where post_id = $post_id and meta_key = 'autometa'";
        
        if ($db->query($q)) {
            foreach ($db->all() as $row) {
                foreach (explode(" ", $row['meta_value']) as $tag) {
                    $tag = trim(str_replace($this->_quotes, ' ', $tag));
                    if (!empty($tag))
                        $tags[] =& $tag;
                }
            }
        }
        
        return $tags;
        
    }
    
    function run($hook, &$post) {

        $tags =& $this->_get_tags($post['post_id']);

        if (count($tags) == 0) {
            return;
        }
        
        $post['_tags_set'] = $this->replace_tags;
        
        if (!$this->replace_tags && isset($post['tags']) && is_array($post['tags'])) {
            $post['tags'] = array_merge($post['tags'], $tags);
            $post['tags'] = array_unique($post['tags']);
        } else {
            $post['tags'] =& $tags;
        }
        
    }
    
    function install() {
        $wp_plugins = get_option('active_plugins');
        if (is_array($wp_plugins)) {
            foreach ($wp_plugins as $plugin) {
                if (preg_match('#/autometa\.php$#', $plugin))
                    return;
            }
        }
        return "The AutoMeta WP plugin needs to be activated for AutoMetaFrontend to work";
    }
    
}

?>